<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<link rel="stylesheet" href="../../layui/css/layui.css">
<link rel="stylesheet" href="../../css/metroStyle/metroStyle.css">
<script src="../../layui/layui.js"></script>
<script src="../../js/jquery.min.js"></script>
<script src="../../js/jquery.ztree.all.js"></script>
<body>
<div class="layui-fluid">
    <div class="layui-row">
        <div class="layui-col-sm8" style="margin-top: 20px;">
            <div style="float: left;margin-left: 30px;"> <h1>角色列表</h1></div>
            <div style="float: left;margin-left: 40px;">
                <form action="" class="layui-form">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">角色名</label>
                            <div class="layui-input-inline">
                                <input type="text" id="roleName" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <button type="button" class="layui-btn" onclick="reloadData()" lay-submit="" lay-filter="demo1">查询</button>
                    </div>
                </form>
            </div>
            <hr/>
            <table class="layui-table" lay-filter="roleTable" lay-data="{id:'roleTable',text:{none:'没有要显示的数据'},url:'http://localhost:9999/Role/list',page:true,even:true,toolbar:'#toolbarDemo',defaultToolbar:['filter', 'print', 'exports']}">
                <thead>
                <th lay-data="{type:'radio',checked:true}"></th>
                <th lay-data="{field:'roleId'}">编号</th>
                <th lay-data="{field:'roleName'}">角色名称</th>
                <th lay-data="{toolbar: '#barDemo'}">操作</th>
                </thead>
            </table>
        </div>
        <div class="layui-col-sm2 layui-col-sm-offset1">
            <h2>显示所有的权限</h2>
            <hr>
            <ul id="treeDemo" class="ztree"></ul>
            <hr>
            <button class="layui-btn" style="width: 100%;" onclick="assignPerms()">授权</button>
        </div>
    </div>

</div>
<script language="JavaScript">
    var zTreeObj;
    var roleId = 1;
    // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
    var setting = {
        check : {
            enable : true
        }
    };
    $(document).ready(function(){
        $.get("http://localhost:9999/Permission/rolePerid/"+roleId,function (pids) {
        $.get("http://localhost:9999/Permission/Trees",function (zNodes) {
            for (let first of zNodes) {
                /*first['open'] = true;*/
                if($.inArray(first.perId,pids) != -1){
                    first['open'] = true;
                    first.checked = true;
                }
                for (let second of first.children) {
                    /* second['open'] = true;*/
                    if ($.inArray(second.perId, pids) != -1) {
                        second.checked = true;
                    }

                    for (let third of second.children) {
                        if ($.inArray(third.perId, pids) != -1) {
                            third.checked = true;
                        }

                    }
                }
            }
            zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        });
        });
    });
    function assignPerms() {
        var checkeddata = zTreeObj.getCheckedNodes();
        if (checkeddata.length >0){
            $.post('http://localhost:9999/Permission/Permissiondel',{roleId:roleId},function () {
                var url = 'http://localhost:9999/Permission/add';
                var postdata = {
                    roleId: roleId,
                    perId: ''
                }

                $.each(checkeddata,function (i) {
                    postdata.perId+=this.perId;
                    if (i < checkeddata.length-1){
                        postdata.perId+=","
                    }
                });
                $.post(url,postdata,function () {
                    layer.msg("角色授权成功！");
                   /* window.onload;*/
                    var User_PermissionData = JSON.parse(sessionStorage.getItem("login_user"));
                    /*layer.msg(User_PermissionData.kmsUser.userName);*/
                    $.post('http://localhost:9999/User/userLogin',{usernames:User_PermissionData.kmsUser.userName,userpd:"true"},function (d) {
                            /*location.href="../../Index2.html";*/
                    })
                })
            })
        } else {
            layer.msg("请选择权限");
        }



    }

    function loadPerTree(roleId) {
        $.get("http://localhost:9999/Permission/rolePerid/"+roleId,function (pids) {
            $.get("http://localhost:9999/Permission/Trees", function (zNodes) {
                for (let first of zNodes) {

                    if($.inArray(first.perId,pids) != -1){
                        first['open'] = true;
                        first.checked = true;
                    }
                    for (let second of first.children) {
                        if ($.inArray(second.perId, pids) != -1) {
                            second.checked = true;
                        }

                        for (let third of second.children) {
                            if ($.inArray(third.perId, pids) != -1) {
                                third.checked = true;
                            }

                        }
                    }
                }
                zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            })
        })
    }


</script>
<script>
    var table ;
    /* var time = setInterval(function () {
         if ($("input[type=radio]").length >1){
             $("input[type=radio]").eq(0).checked=true;
             clearInterval(time);
         }
     },100)*/
    layui.use(['table','form'],function () {
        table = layui.table;
        var form = layui.form;
        /*  $('input'':[name='raido']).get(0).checked=true;*/
       /* $("input[name='layTableRadio_1']").eq(0).attr("checked","checked")*/
        //监听单选按钮事件
        table.on('radio(roleTable)', function(obj){
            roleId= obj.data.roleId;
            loadPerTree(roleId);
        });

        //监听行内的工具条
        table.on('tool(roleTable)',function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）

            if(layEvent === 'del'){ //删除
                layer.confirm('真的删除行么', function(index){
                    layer.close(index);
                    $.post("http://localhost:9999/Role/roledelete",{roleId:data.roleId},function(d){
                        table.reload("roleTable",{
                            page:{
                                curr:1
                            }
                        });
                    });
                });
            }else if (layEvent === 'edit'){//TODO 编辑
                $.post('roleadd.html',function (datas) {
                    layer.open({
                        type:1,
                        title:'修改角色',
                        skin:'layui-layer-molv',
                        area:'800px',
                        anim:3,
                        content:datas,
                        maxmin:true,
                        btn:['确定','取消'],
                        success:function(){
                           /* data.locked = data.locked == 0 ? null : data.locked;*/
                            form.val('roleForm',data);
                          /*  var roleidss = [];
                            for (let role of data.sysRoles) {
                                roleidss.push(role.roleid);
                            }
                            var time = setInterval(function () {
                                if ($("#roles_add option").length > 1) {
                                    select.value('roles2',roleidss);
                                    clearInterval(time);
                                }
                            },100)*/
                        },
                        yes:function () {
                            var formdata = $("#add_role_form").serialize();
                            $.post('http://localhost:9999/Role/roleupdate',formdata,function (data) {
                                layer.close(layer.index);
                                table.reload("roleTable");
                            })
                        }
                    })
                })
            } else if (layEvent === 'detail'){ //TODO 查看详情

            }
        });
        //头工具栏事件
        table.on('toolbar(roleTable)',function(obj){
            //获取选中行
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'batchDelete': //批量删除
                    var data = checkStatus.data;
                    if(data.length == 0){
                        layer.msg('请选择要删除的数据行');
                        return;
                    }
                    layer.confirm("确定要删除选中的数据吗？",function (index) {
                        var p = "?";
                        for(let role of data){
                            p += `roleId=${role.roleId}&`;
                        }
                        $.post(`http://localhost:9999/Role/batchdelete${p}`,d => {
                            layer.close(index);
                            table.reload("roleTable");
                        });
                    })
                    break;
                case 'add':
                  /*  alert("asdf");*/
                    $.post('roleadd.html',function (da) {
                        layer.open({
                            type:1,
                            title:'角色添加',
                            skin:'layui-layer-molv',
                            area:'800px',
                            anim:0,
                            content:da,
                            maxmin:true,
                            btn:['确定','取消'],
                            yes:function () {
                                var formdata = $("#add_role_form").serialize();
                                /*console.log(formdata);*/
                                $.post('http://localhost:9999/Role/roleadd',formdata,function (data) {
                                    layer.close(layer.index);
                                    table.reload("roleTable");
                                })
                            }
                        })
                    })
                  /*  var data = checkStatus.data;
                    layer.msg('选中了：'+ data.length + ' 个');*/
                    break;
                case 'isAll':
                    layer.msg(checkStatus.isAll ? '全选': '未全选');
                    break;
            };
        });
    })
    function reloadData() {
        table.reload("roleTable",{
            page:{
                curr:1
            },
            where:{
                roleName:$("#roleName").val()
            }
        })
    }



</script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="detail">查看</a>
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>

    <!-- 这里同样支持 laytpl 语法，如： -->
    {{#  if(d.auth > 2){ }}
    <a class="layui-btn layui-btn-xs" lay-event="check">审核</a>
    {{#  } }}
</script>

<!--<script type="text/html" id="checkboxTpl">
    <input type="checkbox" name="lock" value="{{d.available}}" title="启用" lay-filter="roleTable" {{ d.available == 1 ? 'checked' : '' }}>
</script>-->
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
       <!-- <button class="layui-btn layui-btn-sm" lay-event="batchDelete">批量删除</button>-->
        <button class="layui-btn layui-btn-sm" lay-event="import">批量导入</button>
    </div>
</script>
</body>
</html>